import axios from "axios";
import Vue from 'vue'

import router from '@/router'

// import router from '@/router'
const $this = new Vue()
let instance = axios.create({
  baseURL: '',
  timeout: 10 * 1000
})

// 请求拦截

instance.interceptors.request.use(
  config => {
    if (localStorage.getItem('token')) {
      config.headers.Authorization = localStorage.getItem('token')
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
instance.interceptors.response.use(
  response => {
    let {
      data
    } = response
    if (data.code * 1 === 401) {
      $this.$confirm(
        "登录超时，请重新登录",
        "提示",
        {
          confirmButtonText: "确定",
          type: "warning",
          showClose: false,
          showCancelButton: false,
        }
      ).then(() => {
        localStorage.removeItem('token')
        localStorage.removeItem("userInfo");
        router.push('/homePage')
        window.location.reload()
      });
      return
    }
    if (response.config.url.includes('warranty/insure/exportAleryPay') || response.config.url.includes('wxpay/payStatus') || response.config.url.includes('warranty/insure/exportClaim') || response.config.url.includes('customer/wallet/info')) {
      return data
    }
    if (data && data.code) {
      if (data.code * 1 == 9000) {
        return data
      }
      if (data.code * 1 !== 200) {
        $this.$message.error(data.msg || '接口报错')
      }
      return data
    } else {
      $this.$message.error(data.msg || '接口报错')
    }
  },
  () => {
    $this.$message.error('接口报错')
  }
)

export default instance